package com.arcvideo.acsplayer.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

public class EncryptUtil {

	/**
	 * 使用 HMAC-SHA256 签名方法对对plainText进行签名
	 *
	 * @param plainText
	 *            被签名的字符串
	 * @param accessSecret
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String hmacSHA256Encrypt(String plainText, String accessSecret) throws Exception {

		Mac mac = Mac.getInstance("HmacSHA256");
		byte[] secretByte = accessSecret.getBytes("UTF-8");
		byte[] dataBytes = plainText.getBytes("UTF-8");
		SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");

		mac.init(secret);
		byte[] doFinal = mac.doFinal(dataBytes);
		byte[] hexB = new Hex().encode(doFinal);
		String signature = new String(hexB);
		return signature;
	}

	/**
	 * 使用 HMAC-SHA256 签名方法对对hash表进行签名
	 *
	 * @param param
	 *            被签名的hash表
	 * @param secret
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String generateSignature(HashMap<String, Object> param, String secret) throws Exception {

		if (StringUtils.isBlank(secret) || MapUtils.isEmpty(param)) {
			return null;
		}
		List<String> keyList = new ArrayList<String>(param.keySet());
		Collections.sort(keyList, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder(secret);
		for (String key : keyList) {
			if (param.get(key) != null) {

				if (!key.equals("signature")) {
					sb.append(key);
					sb.append("=");
					sb.append(param.get(key));
				}
			}
		}

		String signature = hmacSHA256Encrypt(sb.toString(), secret);
		return signature;
	}
}